import os, sys
from PIL import Image

zifu_list = ['@','#',"$",'%','&','?','*','o','/','{','[','(','|','!','^','~','-','_',':',';',',','.','`',' ']
count = len(zifu_list)

def to_text(image_file):
    image_file = image_file.convert('L')
    text = ''
    for h in range(0, image_file.size[1]):
        for w in range(0, image_file.size[0]):
            gray = image_file.getpixel((w, h))
            text = text + zifu_list[int(gray/(255/(count-1)))]
        text = text+'\n'
    return text

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print('用法：ImgtoText.py 图片名 字符画名')
    else:
        image_file = Image.open(sys.argv[1])
        width, height = image_file.size
        image_file = image_file.resize((int(width*0.9), int(height*0.6)))

        text_file = open(sys.argv[2], 'w')
        text_file.write(to_text(image_file))
        text_file.close()
        print('转换成功，字符画保存在 %s' %sys.argv[2])